﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLib.XmlDataModel;
using System.Xml;
using SharedLib.Helpers;
using Tracy.DataModel.UltraExplorer;
using Microsoft.Practices.Unity;
namespace Tracy.DataAccess.UltraExplorer
{
    public class AbstractClassifierProvider<T> : IClassifierProvider<T> where T : XmlDataModelWithAttributesAndID, new()
    {
        Dictionary<string, IClassifier<T>> _dict = new Dictionary<string, IClassifier<T>>();
        Dictionary<string, List<string>> _classifierSets = new Dictionary<string, List<string>>();

        public Dictionary<string, List<string>> ClassifierSets
        {
            get { return _classifierSets; }
        }

        public IClassifier<T> GetItem(string classifierKey)
        {
            if (_dict.ContainsKey(classifierKey)) return _dict[classifierKey];
            string[] splitedValues = classifierKey.Split('|');
            IClassifier<T> rtn = TracyFacade.Instance.DIContainer.Resolve<IClassifier<T>>(splitedValues[0]);
            if (splitedValues.Length > 1)
            {
                rtn.Parameter = splitedValues[1];
            }
            if (rtn != null) _dict.Add(classifierKey, rtn);
            return rtn;
        }

        public AbstractClassifierProvider()
        {
            LoadSettings();
        }

        protected virtual void LoadSettings()
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(@"Settings\UltraExplorer.xml");
            foreach (XmlElement classifierSetNode in doc.SelectNodes("providers/provider[@class='" + this.GetType().FullName + "']/classifier-sets/classifier-set"))
            {
                List<string> classifiers = new List<string>();
                foreach (XmlElement classifierNode in classifierSetNode.SelectNodes("classifier"))
                {
                    string classifierKey = XmlHelper.GetNodeValue(classifierNode);
                    string parameter = classifierNode.GetAttribute("param");
                    if (!String.IsNullOrEmpty(parameter)) classifierKey = classifierKey + "|" + parameter;
                    classifiers.Add(classifierKey);
                }
                ClassifierSets.Add(classifierSetNode.GetAttribute("name"), classifiers);
            }
        }
    }
}
